/**
 * @author helio
 */
if(!SALE.dao) SALE.dao = {}
if(!SALE.dao.local) SALE.dao.local = {}
if(!SALE.dao.local.PaymentDao) SALE.dao.local.PaymentDao = function(){
	var paymentDoc;
}

SALE.dao.local.PaymentDao.prototype = {
		/**
		 * 
		 */
		initPaymentDoc : function() {
			if(!this.paymentDoc) {
				this.paymentDoc = LocalXMLFileUtil.getPaymentDoc();
			}
			
			return this.paymentDoc;
		},
		
		savePaymentDoc : function() {
			LocalXMLFileUtil.saveXML(this.paymentDoc,LocalXMLFileUtil.getPaymentFile());
		},
		
		insertPaymentInfo : function(paymentJson) {
			var root = this.paymentDoc.documentElement;
			var maxid = root.getAttribute("maxid");
			if(!maxid) {
				maxid = 0;
			}
			var id = parseInt(maxid) + 1;
			paymentJson["id"] = id;
			root.setAttribute("maxid",id);
			var paymentNode = this.paymentDoc.createElement("payment");
			
			this.updatePayment(paymentJson, paymentNode);			
			root.appendChild(paymentNode);
			
			this.savePaymentDoc();
		},
		
		modifyPaymentInfo : function(paymentJson) {
			var paymentNode = this.searchPaymentByID(paymentJson.id);
			
			this.updatePayment(paymentJson, paymentNode);
			
			this.savePaymentDoc();
		},
		
		deletePaymentInfo : function(id) {
			var paymentNode = this.searchPaymentByID(id);
			var root = this.paymentDoc.documentElement;
			if(paymentNode != null) {
				root.removeChild(paymentNode);
			}			
		},
		
		updatePayment : function(paymentJson, paymentNode) {
			for (var attri in paymentJson) {
			
				if (attri.indexOf("old") != 0 && paymentJson[attri] && paymentJson[attri] != "") {
					var attriNodes = Ext.DomQuery.select("/" + attri, paymentNode);
					if (attriNodes != null && attriNodes.length > 0) {
						paymentNode.removeChild(attriNodes[0]);
					}
					
					var attriNode = this.paymentDoc.createElement(attri);
					paymentNode.appendChild(attriNode);
					
					if (attri == "details") {
						var details = paymentJson.details;						
						for (var i = 0; i < details.length; i++) {
							var detail = details[i];
							var detailNode = this.paymentDoc.createElement("detail");
							attriNode.appendChild(detailNode);
							
							for (var attriDetail in detail) {
							
								var detailAttriNode = this.paymentDoc.createElement(attriDetail);
								contextNode = this.paymentDoc.createCDATASection(detail[attriDetail]);
								detailAttriNode.appendChild(contextNode);
								detailNode.appendChild(detailAttriNode);
							}
						}
					} else {						
						var contextNode = this.paymentDoc.createCDATASection(paymentJson[attri]);
						attriNode.appendChild(contextNode);
					}
				}
				
			}	
		},
		
		searchPaymentByID : function(id) {
			var root = this.paymentDoc.documentElement;
			var objArray = Ext.query("payment:has(id:nodeValue(" + id+ "))", root);
			var result;
			
			if(objArray.length == 1) {
				result = objArray[0];
			}
			
			return result;
		},
		
		searchCollectBillJson : function(id) {
			var bill = this.searchPaymentByID(id);
			
			if (bill) {
				var children = bill.childNodes;
				var paymentJson = {};
				
				for (var i = 0; i < children.length; i++) {
					var child = children[i];
					
					if (child.nodeType == 1) {
						if (child.nodeName == "details") {
							
							if (!paymentJson.details) {
								paymentJson.details = [];
							}
							
							var detailArray = Ext.query("/detail", child);
							
							Ext.each(detailArray, function(detail) {
								var attriArray = detail.childNodes;
								var detailJson = {}
								for (var j = 0; j < attriArray.length; j++) {
									var attri = attriArray[j];
									if (attri.nodeType == 1) {
										if (!detailJson[attri.nodeName] && attri.childNodes[0] != null) {
											detailJson[attri.nodeName] = attri.childNodes[0].nodeValue;
										}
									}
								}
								
								paymentJson.details.push(detailJson);								
							});
						} else {
							
							if (!paymentJson[child.nodeName] && child.childNodes[0] != null) {
								paymentJson[child.nodeName] = child.childNodes[0].nodeValue;
							}
						}
					}
				}	
				
				return paymentJson;
			}
		},
		
		searchPaymentsArray : function(condition) {
			var root = this.paymentDoc.documentElement;
			var objArray;
			
			if(!condition.status || condition.status == "2") {
				objArray = Ext.query("payment:has(type:nodeValue(" + condition.type + "))", root);
			} else {
				if(condition.status == "1") {
					objArray = Ext.query("payment:has(status:nodeValue(true))", root);
				} else {
					objArray = Ext.query("payment:not(payment:has(status:nodeValue(true)))", root);
				}				
			}
			
			var result = [];
		    Ext.each(objArray, function(payment) {
				var filterFlag = false;
				for (var attri in condition) {
					if(attri != "status") {
						var tempAttri = attri.replace("_to", "");
						tempAttri = tempAttri.replace("_from", "");
						var node = Ext.DomQuery.select("/"+ tempAttri +"/*", payment)[0];
						if(condition[attri] != null && condition[attri] != "") {
							if(!node || node.nodeValue == null || node.nodeValue == "") {
								filterFlag = true;
								break;
							}
							
							if(attri.indexOf("date") > -1 && attri.indexOf("from") > -1) {
								if(Date.parse(node.nodeValue) < Date.parse(condition[attri].replaceAll("-", "/"))) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("_from") > -1) {
								if(node.nodeValue < condition[attri]) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("date") > -1 && attri.indexOf("_to") > -1) {
								if(Date.parse(node.nodeValue) > Date.parse(condition[attri].replaceAll("-", "/"))) {
									filterFlag = true;
									break;
								}
							} else if(attri.indexOf("_to") > -1) {
								if(node.nodeValue > condition[attri]) {
									filterFlag = true;
									break;
								}
							} else if(node.nodeValue && node.nodeValue != ""){
								if(node.nodeValue.toUpperCase().indexOf(condition[attri].toUpperCase()) < 0) {
									filterFlag = true;
									break;
								}
							}
						}
					}
				}
					
				if(!filterFlag) {
					var children = payment.childNodes;
					var nodeJson = {};
					for(var i = 0; i < children.length; i++) {
						var child = children[i];
						
						if(child.nodeType == 1) {
							if (!nodeJson[child.nodeName] && child.childNodes[0] != null) {
								nodeJson[child.nodeName] = child.childNodes[0].nodeValue;
							}
						}			
					}
					
					result.push(nodeJson);
				}

		    });
			return result;
		},
		
		searchBillElement : function(condition) {
			if(!this.paymentDoc) {
				this.initPaymentDoc();
			}
			var root = this.paymentDoc.documentElement;
			var objArray = Ext.query("payment:has(code)", root);
			var result = [];
		    Ext.each(objArray, function(obj) {
				//alert(Ext.DomQuery.select("/code/*", obj).length);
				var code = Ext.DomQuery.select("/code/*", obj)[0];
				var client = Ext.DomQuery.select("/client/*", obj)[0];
				var amount = Ext.DomQuery.select("/amount/*", obj)[0];
				var entry_date = Ext.DomQuery.select("/entry_date/*", obj)[0];
				var dispatch_date = Ext.DomQuery.select("/dispatch_date/*", obj)[0];
				var comment = Ext.DomQuery.select("/comment/*", obj)[0];
				var status = Ext.DomQuery.select("/status/*", obj)[0];
				
				var filterFlag = false;
				if(condition.code_from && condition.code_from != "") {
					if(!code || code == null || condition.code_from > code.nodeValue) {
						filterFlag = true;
					}
				}
				
				if(condition.code_to && condition.code_to != "") {
					if(!code || code == null || condition.code_to < code.nodeValue) {
						filterFlag = true;
					}
				}
				
				if(condition.client && condition.client != "") {
					if(!client || client == null || client.nodeValue == "" || client.nodeValue.indexOf(condition.client) < 0) {
						filterFlag = true;
					}
				}
				
				if(condition.entry_date_from && condition.entry_date_from != "") {
					if(!entry_date || entry_date == null || Date.parse(entry_date.nodeValue) < Date.parse(condition.entry_date_from)) {
						filterFlag = true;
					}
				}
				
				if(condition.entry_date_to && condition.entry_date_to != "") {
					if(!entry_date || entry_date == null || Date.parse(entry_date.nodeValue) > Date.parse(condition.entry_date_to)) {
						filterFlag = true;
					}
				}
				
				if(condition.dispatch_date_from && condition.dispatch_date_from != "") {
					if(!dispatch_date || dispatch_date == null || Date.parse(dispatch_date.nodeValue) < Date.parse(condition.dispatch_date_from)) {
						filterFlag = true;
					}
				}
				
				if(condition.dispatch_date_to && condition.dispatch_date_to != "") {
					if(!dispatch_date || dispatch_date == null || Date.parse(dispatch_date.nodeValue) > Date.parse(condition.dispatch_date_to)) {
						filterFlag = true;
					}
				}
				
				if(condition.status && condition.status != "") {
					
					if((condition.status == '1' || condition.status == 'false' ) && (status && status != null && (status.nodeValue == "true" || status.nodeValue == 1))) {
						filterFlag = true;
					}
					if((condition.status == '2' || condition.status == 'true' ) && (!status || status == null || status.nodeValue == "false" || status.nodeValue == 0)) {
						filterFlag = true;
					}
				}
				
				if(!filterFlag) {
					result.push({
						code : !code || code == null ?  '': code.nodeValue,
						client : !client || client == null ?  '': client.nodeValue,
						amount : !amount || amount == null ?  '': amount.nodeValue,
						entry_date : !entry_date || entry_date == null ?  '': entry_date.nodeValue,
						dispatch_date : !dispatch_date || dispatch_date == null ?  '': dispatch_date.nodeValue,
						comment : !comment || comment == null ?  '': comment.nodeValue,
						status : !status || status == null ?  '': status.nodeValue,
					});
				}

		    });
			return result;
		},
		
		searchSaleDailyStatus : function(daily, ignoreDate) {
			var dateArray = daily.toDateString().split(" ");
			
			var root = this.paymentDoc.documentElement;
			var objArray = Ext.query("payment:has(entry_date:contains("+ dateArray[3] +"))", root);
			var productsJson = {products: [],amount: 0};
			Ext.each(objArray, function(obj) {
				var entry_date = Ext.query("/entry_date/*", obj)[0];
				if (entry_date) {
					var date = entry_date.nodeValue;					
					if (date.indexOf(dateArray[1]) > 0 && (ignoreDate || (date.indexOf(daily.toDateString()) == 0))) {
					
						var details = Ext.query("/details/detail:has(code)", obj);
						Ext.each(details, function(detail){
							var code = Ext.query("/code/*", detail)[0].nodeValue;
							var number = Ext.query("/number/*", detail)[0].nodeValue;
							var amount = Ext.query("/amount/*", detail)[0].nodeValue;
							
							productsJson.amount = productsJson.amount + parseFloat(amount);
							
							var inArray = false;
							Ext.each(productsJson.products, function(product){
								if (product["code"] == code) {
								
									product["number"] = parseFloat(product["number"]) + parseFloat(number);
									product["amount"] = parseFloat(product["amount"]) + parseFloat(amount);
									product["price"] = parseFloat(product["amount"] / product["number"]).toFixed(2);
									inArray = true;
								}
							});
							
							if (!inArray) {
							
								var children = detail.childNodes;
								var productJson = {};
								for (var i = 0; i < children.length; i++) {
									var child = children[i];
									
									if (child.nodeType == 1) {
										if (!productJson[child.nodeName] && child.childNodes[0] != null) {
											productJson[child.nodeName] = child.childNodes[0].nodeValue;
										}
									}
								}
								
								productsJson.products.push(productJson);
							}
						});
					}
				}
		    });
			return productsJson;
		}
}